import request from '../../utils/request';

const app = getApp();

Page({
    data: {
        ipt: '',
        msgs: [],
        toView: '',
        sendDisable: false
    },
    onLoad() {
        this.syncUserInfo();
    },



    // 不单单要后端检查是否登录 或者登录过期状况 ，前端也要做一些基本检查
    async syncUserInfo() {
        const userInfo = wx.getStorageSync('userInfo');
        const token = wx.getStorageSync('token');
        if (!userInfo || !token) {
            wx.redirectTo({ url: '/pages/login/index' });
        } else {
            this.setData({ userInfo: JSON.parse(userInfo) });
        }
    },

    async send() {
        if (!this.data.ipt) {
            wx.showToast({
                title: '不能发送空消息',
                icon: 'error',
                mask: true
            })
        } else {
            // 我说的话
            this.data.msgs.push({
                type: 'me',
                msg: this.data.ipt
            })
            const iptVal = this.data.ipt;
            this.setData({ ipt: '', sendDisable: true, msgs: this.data.msgs, toView: "msg-" + (this.data.msgs.length - 1) });

            //gtp真实回答
            const url = '/chat';
            const { data } = await request({ url, method: "POST", data: { prompt: iptVal } });
            this.data.msgs.push({
                type: 'gpt',
                msg: app.towxml(data.choices[0].text, 'markdown')
            })
            this.setData({ msgs: this.data.msgs, toView: "msg-" + (this.data.msgs.length - 1), sendDisable: false });

            // setTimeout(async()=>{
            //     // gpt思考中
            //     this.data.msgs.push({
            //         type: 'gpt',
            //         msg:app.towxml('思考中...','markdown')
            //     })
            //     this.setData({ msgs: this.data.msgs, toView: "msg-" + (this.data.msgs.length - 1)});


            //     //gtp真实回答
            //     const url = '/chat';
            //     const { data } = await request({ url, method: "POST", data: {prompt: iptVal} });
            //     this.data.msgs[this.data.msgs.length-1].msg = app.towxml(data.choices[0].text,'markdown');
            //     this.setData({ msgs: this.data.msgs, toView: "msg-" + (this.data.msgs.length - 1), sendDisable:false });
            // },1000)
        }
    },

    onChangeIpt(e: any) {
        this.setData({ ipt: e.detail.value });
    },
})
